package com.xf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xf.common.core.domain.Constants;
import com.xf.common.core.domain.DmpResult;
import com.xf.common.core.entity.CurrentUser;
import com.xf.common.core.entity.QueryRequest;
import com.xf.common.core.entity.constant.FebsConstant;
import com.xf.common.core.entity.constant.StringConstant;
import com.xf.common.core.entity.dmp.DmpAuthRole;
import com.xf.common.core.entity.dmp.DmpAuthUser;
import com.xf.common.core.entity.dmp.DmpAuthUserRoleRelation;
import com.xf.common.core.entity.system.SystemUser;
import com.xf.common.core.entity.system.UserRole;
import com.xf.common.core.enums.UserCacheKeyEnum;
import com.xf.common.core.exception.FebsException;
import com.xf.common.core.utils.BeanUtils;
import com.xf.common.core.utils.FebsUtil;
import com.xf.common.core.utils.SortUtil;
import com.xf.common.redis.cache.DmpRedisCache;
import com.xf.mapper.DmpAuthUserMapper;
import com.xf.service.DmpAuthRoleService;
import com.xf.service.DmpAuthUserRoleRelationService;
import com.xf.service.DmpAuthUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author JoeyLiu
 * @create 2022-04-01 13:59
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class DmpAuthUserServiceImpl extends ServiceImpl<DmpAuthUserMapper, DmpAuthUser> implements DmpAuthUserService {

    //    @Resource
//    private IUserRoleService userRoleService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private DmpRedisCache redisCache;
    @Autowired
    private DmpAuthUserRoleRelationService userRoleRelationService;

    @Autowired
    private DmpAuthRoleService dmpAuthRoleService;

//    @Override
//    public DmpAuthUser findByName(String username) {
//        LambdaQueryWrapper<DmpAuthUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(DmpAuthUser::getUserName, username);
//        return this.baseMapper.selectOne(queryWrapper);
//    }

    @Override
    public IPage<DmpAuthUser> findUserDetailList(DmpAuthUser user, QueryRequest request) {
        Page<DmpAuthUser> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, "userId", FebsConstant.ORDER_ASC, false);
        return this.baseMapper.findUserDetailPage(page, user);
    }

    @Override
    public DmpAuthUser findUserDetail(String username) {
        DmpAuthUser param = new DmpAuthUser();
        param.setUserName(username);
        List<DmpAuthUser> users = this.baseMapper.findUserDetail(param);
        return CollectionUtils.isNotEmpty(users) ? users.get(0) : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLoginTime(String username) {
        DmpAuthUser user = new DmpAuthUser();
//        user.setLastSigninTime(new Date());

        this.baseMapper.update(user, new LambdaQueryWrapper<DmpAuthUser>().eq(DmpAuthUser::getUserName, username));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUser(DmpAuthUser user) {
        // 创建用户
        user.setCreatedDate(new Date());
        user.setAvatar(SystemUser.DEFAULT_AVATAR);
        user.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));
        save(user);
        // 保存用户角色
        String[] roles = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getRoleId(), StringConstant.COMMA);
        setUserRoles(user, roles);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(DmpAuthUser user) {
        // 更新用户
        user.setPassword(null);
        user.setUserName(null);
        user.setCreatedDate(null);
        user.setUpdatedDate(new Date());
        updateById(user);

        String[] userIds = {String.valueOf(user.getUserCode())};
//        userRoleService.deleteUserRolesByUserId(userIds);
        String[] roles = StringUtils.splitByWholeSeparatorPreserveAllTokens(user.getRoleId(), StringConstant.COMMA);
        setUserRoles(user, roles);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsers(String[] userIds) {
        List<String> list = Arrays.asList(userIds);
        removeByIds(list);
        // 删除用户角色
//        this.userRoleService.deleteUserRolesByUserId(userIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProfile(DmpAuthUser user) throws FebsException {
        user.setPassword(null);
        user.setUserName(null);
        user.setStatus(null);
        if (isCurrentUser(user.getId())) {
            updateById(user);
        } else {
            throw new FebsException("您无权修改别人的账号信息！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAvatar(String avatar) {
        DmpAuthUser user = new DmpAuthUser();
        user.setAvatar(avatar);
        String currentUsername = FebsUtil.getCurrentUsername();
        this.baseMapper.update(user, new LambdaQueryWrapper<DmpAuthUser>().eq(DmpAuthUser::getUserName, currentUsername));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(String password) {
        DmpAuthUser user = new DmpAuthUser();
        user.setPassword(passwordEncoder.encode(password));
        String currentUsername = FebsUtil.getCurrentUsername();
        this.baseMapper.update(user, new LambdaQueryWrapper<DmpAuthUser>().eq(DmpAuthUser::getUserName, currentUsername));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(String[] usernames) {
        DmpAuthUser params = new DmpAuthUser();
        params.setPassword(passwordEncoder.encode(SystemUser.DEFAULT_PASSWORD));
        List<String> list = Arrays.asList(usernames);
        this.baseMapper.update(params, new LambdaQueryWrapper<DmpAuthUser>().in(DmpAuthUser::getUserName, list));

    }

    @Override
    public DmpResult add(DmpAuthUser user) {
        try {
//                DmpAuthUser existsUser = userRoleService.getByUserName(user.getUserName());
//                if (Objects.nonNull(existsUser)) {
//                    return DmpResult.failed("该账号已被使用");
//                }
//                DmpAuthUser getPhone = userRoleService.getByTelPhone(user.getTelPhone());
//                if (Objects.nonNull(getPhone)) {
//                    return DmpResult.failed();
//                }

            user.setUserCode(UUID.randomUUID().toString());
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            user.setState(user.getState());
            user.setTenantId(user.getTenantId());
//            userRoleService.save(user);

        } catch (Exception e) {
            log.error("获取锁中断", e);
            return DmpResult.failed("执行任务超时");
        }
        return DmpResult.success();
    }

    private void setUserRoles(DmpAuthUser user, String[] roles) {
        List<UserRole> userRoles = new ArrayList<>();
        Arrays.stream(roles).forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(Long.valueOf(roleId));
            userRoles.add(userRole);
        });
//        userRoleService.saveBatch(userRoles);
    }


    private boolean isCurrentUser(Long id) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        return currentUser != null && id.equals(currentUser.getUserId());
    }

    @Override
    public DmpResult<DmpAuthUser> selectByUserCode(String userCode) {
        DmpAuthUser dmpAuthUser = redisCache.getEx(UserCacheKeyEnum.USER.getKey(userCode),
                Duration.ofSeconds(30),
                () -> this.baseMapper.selectByUserCode(userCode));
        return DmpResult.data(dmpAuthUser);
    }

    @Override
    public DmpResult<DmpAuthUser> selectByNameOrEmail(String user) {
        DmpAuthUser dmpAuthUser = redisCache.getEx(UserCacheKeyEnum.USER.getKey(user),
                Duration.ofSeconds(30),
                () -> this.baseMapper.selectByNameOrEmail(user));
        return DmpResult.data(dmpAuthUser);
    }

    @Override
    public SystemUser findByName(String username) {
        return redisCache.getEx(UserCacheKeyEnum.USER.getKey(username), Duration.ofSeconds(Constants.USER_TIME_OUT), () -> {
            DmpAuthUser dmpAuthUser = this.baseMapper.findByName(username);
            Assert.notNull(dmpAuthUser, "用户未注册");
            return createUserDto(dmpAuthUser);
        });
    }

    private SystemUser createUserDto(DmpAuthUser user) {
        SystemUser systemUser = new SystemUser();
        BeanUtils.copyPropertiesIgnoreNullValue(user, systemUser);
        List<String> roleList = new ArrayList<>();
        systemUser.setRoleList(roleList);
        //用户和角色关系表
        List<DmpAuthUserRoleRelation> userRoleRelationList = userRoleRelationService
                .list(Wrappers.lambdaQuery(DmpAuthUserRoleRelation.class)
                        .select(DmpAuthUserRoleRelation::getRoleId)
                        .eq(DmpAuthUserRoleRelation::getUserId, systemUser.getId()));
        if (CollectionUtils.isNotEmpty(userRoleRelationList)) {
            List<DmpAuthRole> userRoleList = dmpAuthRoleService.listByIds(userRoleRelationList.
                    stream().map(DmpAuthUserRoleRelation::getRoleId).collect(Collectors.toList()));
            if (CollectionUtils.isNotEmpty(userRoleList)) {
                roleList.addAll(userRoleList.stream().map(DmpAuthRole::getName).collect(Collectors.toSet()));
            }
        }
        return systemUser;
    }

    @Override
    public DmpResult<SystemUser> findByMobile(String mobile) {
        DmpAuthUser dmpAuthUser = redisCache.getEx(UserCacheKeyEnum.USER.getKey(mobile),
                Duration.ofSeconds(Constants.CLIENT_DETAILS),
                () -> this.baseMapper.findByMobile(mobile));
        return DmpResult.data(dmpAuthUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmpResult<SystemUser> registUser(String username, String password) {
        SystemUser systemUser = new SystemUser();
        systemUser.setUserName(username);
        systemUser.setPassword(password);
        systemUser.setCreatedDate(new Date());
        systemUser.setStatus(SystemUser.STATUS_VALID);
        systemUser.setAvatar(SystemUser.DEFAULT_AVATAR);
        systemUser.setRemark("注册用户");
        this.baseMapper.insert(systemUser);
//        UserRole userRole = new UserRole();
//        userRole.setUserId(systemUser.getUserId());
//        // 注册用户角色 ID
//        userRole.setRoleId(FebsConstant.REGISTER_ROLE_ID);
//        this.userRoleMapper.insert(userRole);

        return DmpResult.data(systemUser);
    }
}


